package com.tj.bo.user.server;

import com.fqgj.common.utils.DateUtil;
import com.fqgj.common.utils.StringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.tj.bo.common.conf.enums.UserActivityEnum;
import com.tj.bo.user.client.UserActivityService;
import com.tj.bo.user.client.vo.output.UserActivity;
import com.tj.bo.user.server.dao.UserActivityDao;
import com.tj.bo.user.server.dao.UserActivityReadDao;
import com.tj.bo.user.server.entity.UserActivityEntity;
import com.tj.bo.user.server.entity.UserActivityReadEntity;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @program: binary-option
 * @description
 * @author: frank
 * @create: 2020-08-28 16:07
 **/
@Service
public class UserActivityServiceImpl implements UserActivityService {

    @Autowired
    private UserActivityDao userActivityDao;
    @Autowired
    private UserActivityReadDao userActivityReadDao;

    @Override
    public Boolean readActivity(Long id, String userCode) {
        UserActivityReadEntity entity = new UserActivityReadEntity();
        entity.setActivityId(id);
        entity.setUserCode(userCode);
        entity.setType(UserActivityEnum.POPUP.getCode());
        entity.setRead(1);
        entity.setCreateDate(new Date());
        userActivityReadDao.insert(entity);
        return true;
    }

    @Override
    public List<UserActivity> queryActivityByUserCode(String userCode, Integer type) {
        if(StringUtils.isEmpty(userCode) || type == null){
            return Lists.newArrayList();
        }
        List<UserActivityEntity> userActivityEntities = userActivityDao.selectByParams(Maps.newHashMap());
        userActivityEntities = Optional.ofNullable(userActivityEntities).orElseGet(()-> {return Lists.newArrayList();})
                .stream().filter(s -> DateUtil.diffDateToSecond(new Date(),s.getStartDate()) >= 0
                        && DateUtil.diffDateToSecond(new Date(),s.getEndDate()) <= 0
                        && s.getIsSelling() == 1).collect(Collectors.toList());

        List<UserActivity> userActivities = Lists.newArrayList();
        for(UserActivityEntity entity : userActivityEntities){
            UserActivityReadEntity activityRead = userActivityReadDao.getActivityReadByUserCodeAndActivityId(entity.getId(), userCode, new Date());
            if(entity.getIntervalType() == 1 && activityRead != null){
                continue;
            }
            UserActivity userActivity = new UserActivity();
            BeanUtils.copyProperties(entity, userActivity);
            userActivity.setActivityId(entity.getId());
            userActivities.add(userActivity);
        }
        return userActivities;
    }
}
